import { useCallback, useEffect, useState } from "react";
import { View } from "@tarojs/components";
import { useDidShow, useRouter, navigateBack, useDidHide } from "@tarojs/taro";
import {
  Layout,
  WithMargins,
  C13BottomDock,
  Header,
  Paragraph,
  KeyValueList,
  AbstractAccordion,
  Icon,
} from "@/components";
import {
  useUserInfo,
  getRefundDetail,
  cancelRefund,
  getUserData,
} from "@/store/userDataContext";
import { useAuth } from "@/store/authContext";
import style from "./index.module.scss";
import { navigateTo, switchTab } from "@/utils/navigation";
import { getTimeRemaining } from "@/utils/dateTimeFormatHelpers";
import { AddressFieldShape } from "@/data/user/userTypes";
import { colors } from "@/data/shared/colors";
import { RefundDetailResponse, RefundStatuses } from "@/data/refund/refundData";
import { BottomDockButtonShape } from "@/components/c13-BottomDock";

export default function RefundDetail() {
  const { params } = useRouter();
  const { orderNo } = params;
  const { dispatchAuthAction } = useAuth();
  const { userInfoState, dispatchUserDataAction } = useUserInfo();
  const { userData } = userInfoState;
  const [status, setStatus] = useState("");
  const [subStatus, setSubStatus] = useState("");
  const [deliveryAddress, setDeliveryAdress] =
    useState<AddressFieldShape | null>(null);
  const [refundDetailData, setRefundDetailData] =
    useState<RefundDetailResponse | null>(null);
  const [canChangeDelivery, setCanChangeDelivery] = useState(0);
  let countDownInterval: any = 0;

  useDidShow(async () => {
    if (orderNo) {
      const refundDetail = await getRefundDetail({
        query: { orderNo: orderNo },
        authDispatch: dispatchAuthAction,
      });
      refundDetail && setRefundDetailData(refundDetail);
    } else {
      navigateBack();
    }
    if (!userData?.userInfo.phoneNumber) {
      getUserData(dispatchUserDataAction, userData!, {
        authDispatch: dispatchAuthAction,
      });
    }
  });

  useDidHide(() => {
    countDownInterval && clearInterval(countDownInterval);
  });

  const initializeClock = useCallback(
    (dl) => {
      return setInterval(() => {
        const t = getTimeRemaining(dl);
        setSubStatus(
          "请在" + t.days + "天" + t.hours + "小时" + t.minutes + "分钟内寄出"
        );
        if (t.total <= 0) {
          countDownInterval && clearInterval(countDownInterval);
          setStatus("退款已取消");
          setSubStatus("");
          setPrimaryCta(REOCCURING_PRIMARY_GO_TO_ORDER);
          setSecondaryCta(DEFAULT_SECONDARY_CTA_NULL);
        }
        if (canChangeDelivery) {
          setSubStatus("待上门取件");
          countDownInterval && clearInterval(countDownInterval);
        }
      }, 1000);
    },
    [refundDetailData]
  );

  useEffect(() => {
    if (userData?.userInfo.defaultAddress) {
      setDeliveryAdress(userData?.userInfo.defaultAddress);
    }
  }, [userData?.userInfo.phoneNumber]);

  const cancel = async () => {
    const result = await cancelRefund({
      query: { orderNo: orderNo },
      authDispatch: dispatchAuthAction,
    });
    if (result) {
      navigateBack();
    }
  };

  const gotoDelivery = () => {
    if (orderNo && refundDetailData && refundDetailData.returnEndTime) {
      navigateTo(
        `pages/user-refund-delivery/index?orderNo=${orderNo}&returnEndTime=${encodeURI(
          refundDetailData.returnEndTime
        )}&change=${canChangeDelivery}`
      );
    }
  };

  const gotoOrder = () => {
    if (orderNo) {
      navigateTo(`pages/user-order-details/index?orderNo=${orderNo}`);
    }
  };

  // Defualt primary = old array index [0]
  // Defualt secondary = old array index [0]
  const DEFAULT_PRIMARY_CTA = {
    cb: gotoDelivery,
    text: "立即寄回",
  };
  const DEFAULT_SECONDARY_CTA_NULL = null;

  const REOCCURING_PRIMARY_GO_TO_ORDER = {
    cb: gotoOrder,
    text: "返回订单",
  };

  const REOCCURING_CANCEL_CTA = {
    cb: cancel,
    disabled:
      refundDetailData &&
      refundDetailData.refundStatus === RefundStatuses.RefundInProgress
        ? true
        : undefined,
    text: "撤销申请",
  };

  const [primaryCta, setPrimaryCta] =
    useState<BottomDockButtonShape>(DEFAULT_PRIMARY_CTA);
  const [secondaryCta, setSecondaryCta] =
    useState<BottomDockButtonShape | null>(DEFAULT_SECONDARY_CTA_NULL);

  // Defined in component to get access to scope
  const RefundStatusMap: {
    [key in RefundStatuses]: {
      statusMessage: string;
      defSubStat: string;
      primCtaData: BottomDockButtonShape;
      secondaryCtaData: BottomDockButtonShape | null;
    };
  } = {
    [RefundStatuses.NotRefunded]: {
      statusMessage: "客服确认中",
      defSubStat: "",
      primCtaData: REOCCURING_PRIMARY_GO_TO_ORDER,
      secondaryCtaData: DEFAULT_SECONDARY_CTA_NULL,
    },
    [RefundStatuses.InApplication]: {
      statusMessage: "客服处理中",
      defSubStat: "",
      primCtaData: REOCCURING_CANCEL_CTA,
      secondaryCtaData: DEFAULT_SECONDARY_CTA_NULL,
    },
    [RefundStatuses.Refunded]: {
      statusMessage: "已退款",
      defSubStat: "退款成功！钱款已返回账户",
      primCtaData: REOCCURING_PRIMARY_GO_TO_ORDER,
      secondaryCtaData: DEFAULT_SECONDARY_CTA_NULL,
    },
    [RefundStatuses.RefundInProgress]: {
      statusMessage: "客服确认中",
      defSubStat: "包裹已寄出",
      primCtaData: REOCCURING_PRIMARY_GO_TO_ORDER,
      secondaryCtaData: DEFAULT_SECONDARY_CTA_NULL,
    },
    [RefundStatuses.ToBeReturned]: {
      statusMessage: "待退货",
      defSubStat: "",
      primCtaData: DEFAULT_PRIMARY_CTA,
      secondaryCtaData: REOCCURING_CANCEL_CTA,
    },
    [RefundStatuses.Returning]: {
      statusMessage: "客服确认中",
      defSubStat: "包裹已寄出",
      primCtaData: REOCCURING_PRIMARY_GO_TO_ORDER,
      secondaryCtaData: DEFAULT_SECONDARY_CTA_NULL,
    },
    [RefundStatuses.RefundCancelled]: {
      statusMessage: "退款已取消",
      defSubStat: "",
      primCtaData: REOCCURING_PRIMARY_GO_TO_ORDER,
      secondaryCtaData: DEFAULT_SECONDARY_CTA_NULL,
    },
  };

  useEffect(() => {
    if (refundDetailData) {
      if (refundDetailData.pickUpEndTime || refundDetailData.pickUpStartTime) {
        setCanChangeDelivery(1);
      } else {
        setCanChangeDelivery(0);
      }

      const { refundStatus, refundReason } = refundDetailData;

      const refundData = RefundStatusMap[refundStatus];
      setStatus(refundData.statusMessage);
      setSubStatus(refundData.defSubStat);
      setPrimaryCta(refundData.primCtaData);
      setSecondaryCta(refundData.secondaryCtaData);

      // Overrides
      switch (refundStatus) {
        case RefundStatuses.ToBeReturned:
          if (!canChangeDelivery) {
            if (
              !refundDetailData.pickUpEndTime &&
              !refundDetailData.pickUpStartTime &&
              refundDetailData.deliveryCountdown &&
              //@ts-ignore
              new Date() - new Date(refundDetailData.deliveryCountdown) < 0
            ) {
              countDownInterval = initializeClock(
                new Date(refundDetailData.deliveryCountdown)
              );
            }
          } else {
            countDownInterval && clearInterval(countDownInterval);
            setSubStatus("待上门取件");
            setPrimaryCta((prevVal) => ({ ...prevVal, text: "修改寄件详情" }));
          }
          break;
        case RefundStatuses.RefundCancelled:
          if (refundReason) {
            setSubStatus(
              `退款申请被驳回，原因为${refundReason}，若有疑问请联系客服`
            );
          }
          break;
        default:
      }
    }
  }, [refundDetailData, canChangeDelivery]);

  return (
    <Layout>
      {refundDetailData && (
        <>
          <WithMargins>
            <View className={style["refund-detail-wrapper"]}>
              <Paragraph size="small" noSpacing>
                售后详情
              </Paragraph>
              <Header type="heading-l">{status}</Header>
              <View className={style["sub-status"]}>
                <Paragraph size="small" noSpacing>
                  {subStatus}
                </Paragraph>
              </View>

              <View>
                {refundDetailData.routesList &&
                  ((refundDetailData.refundStatus !== RefundStatuses.Refunded &&
                    refundDetailData.refundStatus ===
                      RefundStatuses.ToBeReturned &&
                    !canChangeDelivery) ||
                    refundDetailData.refundStatus ===
                      RefundStatuses.Returning) && (
                    <View
                      className={`${style["top-border-section"]} ${style["misc-info"]}`}
                    >
                      <View className={style["misc-title"]}>
                        <Header type="heading-s">物流信息</Header>
                      </View>
                      <View>
                        {refundDetailData.waybill && (
                          <View className={style["misc-content"]}>
                            <View className={style["delivery-title"]}>
                              <Icon type={"SF"} className={style.sf} />
                              顺丰速运：{refundDetailData.waybill}
                            </View>
                            <View className={style["delivery-info"]}>
                              {`【${refundDetailData.routesList.remark}】${
                                refundDetailData.routesList.acceptTime || ""
                              }
                              ${
                                refundDetailData.routesList.acceptAddress || ""
                              }`}
                            </View>
                          </View>
                        )}
                      </View>
                    </View>
                  )}
                {refundDetailData.refundStatus &&
                  refundDetailData.refundStatus ===
                    RefundStatuses.ToBeReturned && (
                    <View className={style["pick-up-time"]}>
                      {canChangeDelivery ? (
                        `预约${refundDetailData.pickUpDate}
                      ${refundDetailData.pickUpStartTime}-${refundDetailData.pickUpEndTime}上门取件`
                      ) : (
                        <>
                          <Header type="heading-s">寄件方式</Header>
                          <View className={style["pick-up-info"]}>
                            上门取件
                          </View>
                          <View className={style["pick-up-policy"]}>
                            请查阅退货须知
                          </View>
                        </>
                      )}
                    </View>
                  )}
                {refundDetailData.refundStatus &&
                refundDetailData.refundStatus === RefundStatuses.ToBeReturned &&
                canChangeDelivery &&
                deliveryAddress ? (
                  <View className={style["address"]}>
                    <Header type="heading-s">取件信息</Header>
                    <KeyValueList
                      itemList={[
                        {
                          leftText: "姓名",
                          middleTextTop: deliveryAddress.name,
                        },
                        {
                          leftText: "电话",
                          middleTextTop: deliveryAddress.phone,
                        },
                        {
                          leftText: "地址",
                          middleTextTop: `${deliveryAddress.residenceArea.join(
                            ""
                          )}${deliveryAddress.address}`,
                        },
                      ]}
                    />
                  </View>
                ) : null}

                {/* 
                  TODO: Luke - Below condition has been rewritten - needs proper testing!
                */}
                {(refundDetailData.refundStatus &&
                  refundDetailData.refundStatus ===
                    RefundStatuses.RefundInProgress) ||
                  refundDetailData.refundStatus === RefundStatuses.Returning ||
                  (refundDetailData.refundStatus ===
                    RefundStatuses.ToBeReturned &&
                    !canChangeDelivery && (
                      <View className={style["address"]}>
                        <Header type="heading-s">收货信息</Header>
                        <View className={style["bottom-border-section"]}>
                          <KeyValueList
                            itemList={[
                              {
                                leftText: "姓名",
                                middleTextTop: refundDetailData.consigneeName,
                              },
                              {
                                leftText: "电话",
                                middleTextTop: refundDetailData.consigneePhone,
                              },
                              {
                                leftText: "地址",
                                middleTextTop:
                                  refundDetailData.consigneeAddress,
                              },
                            ]}
                          />
                        </View>
                      </View>
                    ))}
                <View className={style["address"]}>
                  <Header type="heading-s">退款信息</Header>
                  <View className={style["bottom-border-section"]}>
                    <KeyValueList
                      itemList={[
                        {
                          leftText: "退款金额",
                          middleTextTop: refundDetailData.refundPrice,
                        },
                        {
                          leftText: "退款明细",
                          middleTextTop: refundDetailData.refundDetails,
                        },
                        {
                          leftText: "申请理由",
                          middleTextTop: refundDetailData.refundReasonWap,
                        },
                        {
                          leftText: "补充说明",
                          middleTextTop:
                            refundDetailData.refundReasonWapExplain,
                        },
                        {
                          leftText: "申请时间",
                          middleTextTop: refundDetailData.refundApplicationTime,
                        },
                        refundDetailData.refundStatus >
                          RefundStatuses.InApplication &&
                        refundDetailData.returnOrderNo
                          ? {
                              leftText: "退款编号",
                              middleTextTop: refundDetailData.returnOrderNo,
                            }
                          : null,
                      ]}
                    />
                  </View>
                </View>
                <View className={style["history"]}>
                  <AbstractAccordion
                    title={"售后历史"}
                    bottomBorderColor={colors.colorConversation}
                  >
                    <View className={style["history-list-wrapper"]}>
                      {refundDetailData.storeOrderStatuseList &&
                        refundDetailData.storeOrderStatuseList.map(
                          (list, listIdx) => {
                            const active = listIdx === 0;

                            return (
                              <View
                                key={listIdx}
                                className={style["history-item"]}
                              >
                                <View
                                  className={`${style["history-title"]} ${
                                    active ? style.active : null
                                  }`}
                                >
                                  <Icon
                                    className={style.ellipse}
                                    type={
                                      active ? "EllipseDark" : "EllipseGrey"
                                    }
                                  />
                                  {list.changeMessage}
                                </View>
                                <View className={style["history-date"]}>
                                  {list.createTime}
                                </View>
                              </View>
                            );
                          }
                        )}
                    </View>
                  </AbstractAccordion>
                </View>
              </View>
            </View>
          </WithMargins>

          <View className={style["dock-wrapper"]}>
            <C13BottomDock
              onPrimaryClick={primaryCta}
              onSecondaryClick={secondaryCta}
            />
          </View>
        </>
      )}
    </Layout>
  );
}
